package persistencia;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.net.URL;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.apache.commons.io.IOUtils;
import org.xml.sax.SAXException;

import com.google.appengine.api.datastore.Blob;
import com.sun.org.apache.xpath.internal.operations.UnaryOperation;

public class JAXBAgent {

	@SuppressWarnings("unchecked")
	public static <E> ByteArrayOutputStream marshal(Class<E> c, Object ob) throws JAXBException {
		JAXBContext jc = JAXBContext.newInstance(c);
        Marshaller marshaller = jc.createMarshaller();

        marshaller.setProperty(javax.xml.bind.Marshaller.JAXB_ENCODING, "utf-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
		ByteArrayOutputStream salida= new ByteArrayOutputStream();
        marshaller.marshal((E)ob,salida);
        marshaller.marshal((E)ob, System.out);
        return salida;
	}
		
	
	public static <E> E unmarshal (Blob original, Class<E> c) throws  IOException, JAXBException, SAXException {
			JAXBContext jc = JAXBContext.newInstance(c);
			Unmarshaller unmarshaller = jc.createUnmarshaller();
			SchemaFactory sf= SchemaFactory.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
			
			unmarshaller.setSchema(null);
		
			return (E) unmarshaller.unmarshal(new ByteArrayInputStream(original.getBytes()));
			
	}
}
